<template>
	<view class="content">
		<my-bar bgColor="{{{theme}}}"> 
			<block slot="content">{{ title }}</block>
			<!--#ifdef MP-WEIXIN-->
			<block slot="backText"><button class="cu-btn {{{theme}}} margin-right-xs" @click.stop="postForm.id?update():submit()">保存</button></block>
			<!--#endif-->
			<!--#ifndef MP-WEIXIN-->
			<block slot="right"><button class="cu-btn {{{theme}}} margin-right-xs" @click.stop="postForm.id?update():submit()">保存</button></block>
			<!--#endif-->
		</my-bar> 
		<form>  
			<!-- !!!!! placeholder 在ios表现有偏移 建议使用 第一种样式 -->	
			<% for(let k in  obj.properties){
				var v = obj.properties[k] 
				if(k=="id")continue; //id不显示
				switch(v.type){
					case "string":											    
			%>
			<view class="cu-form-group margin-top-xs">
			    <view class="title">{{{v.title}}}</view>
				<input placeholder="请输入{{{v.title}}}" name="{{{k}}}" v-model="postForm.{{{k}}}" class="text-right"/>
			</view>
			<%       break; case "integer":%>
			<view class="cu-form-group margin-top-xs">
				<view class="title">{{{v.title}}}</view>
				<input placeholder="请输入{{{v.title}}}" name="{{{k}}}" type="number" v-model="postForm.{{{k}}}" class="text-right"/>
			</view>
			<%       break; case "boolean":%>
			<radio-group class="block" @change="postForm.{{{k}}} = !postForm.{{{k}}}">
				<view class="cu-form-group">
					<view class="title">{{{v.title}}}</view>
					<view> 
						是
						<radio class="margin-left-sm margin-right" :class="postForm.{{{k}}} ? 'checked' : ''" :checked="postForm.{{{k}}} ? true : false" value="true"></radio>
						否
						<radio class="margin-left-sm" :class="!postForm.{{{k}}} ? 'checked' : ''" :checked="!postForm.{{{k}}} ? true : false" value="false"></radio>
					</view> 
				</view>
			</radio-group>
		    <%       break; case "datapicker":%>
		    <view class="cu-form-group margin-top-xs">
			  <view class="title">{{{v.title}}}</view>
				<uni-data-picker class="picker"
		   		placeholder="请选择{{{v.title}}}"
		   		popup-title="请选择所在{{{v.title}}}"
		   		:localdata="{{{k}}}dataTree"
		   		v-model="postForm.{{{k}}}" 
		   		:map="{ text: 'name', value: 'id', children: 'childs' }">			
				</uni-data-picker>
			   </view>
			<%       break; case "image":%>
			<view class="cu-form-group img-list">
				<view class="grid col-4 grid-square flex-sub justify-end">
					<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="viewImage" :data-url="imgList[index]">
						<image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red text-df" @tap.stop="delImg" :data-index="index"><text class="cuIcon-close"></text></view>
					</view>
					<view class="solids " @tap="chooseImage" v-if="imgList.length < uploadImgCount">
						<text class="cuIcon-cameraadd">
							<text class="text-sm">{{ imgList.length }}/{{ uploadImgCount}}</text>
						</text>
					</view>
				</view>
			</view>
		    <%       break; case "textarea":%>
		    <view class="cu-form-group">
		    	<textarea rows="1000" v-model="postForm.{{{k}}}"  class="text-right" :adjust-position="false"
		    		placeholder="请输入{{{v.title}}}...">
		    	</textarea>
		    </view>
		    <view class="cu-bar bg-white text-grey shadow shadow-lg">
		    	<view class="action text-xs">{{ postForm.{{{k}}}.length }}/{{ publish.contentTextCount }}</view>
		    	<view class="action"></view>
		    </view>
		    <%       break; case "tel":%>
		    <view class="cu-form-group">
		     	<view class="title">{{{v.title}}}</view>
		     	<input placeholder="请输入{{{v.title}}}..." v-model="postForm.{{{k}}}" name="{{{k}}}"></input>
		     	<view class="cu-capsule radius">
		     		<view class='cu-tag bg-blue '>
		     			+86
		     		</view>
		     		<view class="cu-tag line-blue">
		     			中国大陆
		     		</view>
		     	</view>
		     </view>
			 <%       break; case "datetime":%>
			 <view class="cu-form-group">
			 	<view class="title">{{{v.title}}}</view>
			 	<picker mode="date" :value="postForm.{{{k}}}" start="1980-09-01" end="2030-09-01"
			 		@change="{{{k}}}Change">
			 		<view class="picker">
			 			{{postForm.{{{k}}}||'请选择'}}
			 		</view>
			 	</picker>
			 </view>
			<% }} %>
			<app-modal ref="modal" content="主人真的要无情的抛弃我吗？" :buttons="['再想想', '残忍说再见']"></app-modal>
		    <!-- <button class="cu-btn bg-red margin-tb-sm lg">发布</button> -->
		</form>
	</view>  
</template>

<script>
import appModal from '@/components/my-modal/my-modal.vue';
import uniDataPicker from '@/components/uni-data-picker/components/uni-data-picker/uni-data-picker.vue';
import pageMixin from '@/mixin/page.js';
import api from '@/common/api.js';
import http from '@/common/http.js';
import { mapState } from 'vuex';
export default {
	components: {
		appModal,uniDataPicker
	},
	mixins: [pageMixin],
	data() {
		return {
			uploadImgCount:1,//图片上传数量 that.publish.uploadImgCount = 默认为9
			imgList: [],//本地选择的图片列表
			postForm:{//提交到服务器的的表单数据
			   <% for(let k in  obj.properties){
				   var v = obj.properties[k] 			
					   var  defaultValue='""'
					   switch(v.type){
						   case "integer":
						     defaultValue=0
						     break;
						   case "boolean":
						     defaultValue=true
						     break;	
						   case "datapicker":
						     defaultValue=null
						     break;		
					   }
			   %>
			       <%= k %>:<%-defaultValue%>,//<%= v.description %>
			   <% } %>
			},
			<% for(let k in  obj.properties){
				var v = obj.properties[k] 
				if(v.type=="datapicker"){									    
			%>
			{{{k}}}dataTree: [],
			<% }} %>
		};
	},
	onLoad(e) {
		this.postForm.id = e.id;//接受传递过来的参数
		if(this.postForm.id){//id不为空表示修改	获取详细信息
			this.getDetail()
		}
		<% for(let k in  obj.properties){
			var v = obj.properties[k] 
			if(v.type=="datapicker"){									    
		%>
		http.get(this.$store.state.pages.{{{dir}}}.{{{v.classname}}}.list.url+"?pageSize=-1&ParentId=null").then(res=>{
			this.{{{k}}}dataTree.push.apply(this.{{{k}}}dataTree, res.data.items);
			//console.error(JSON.stringify(res.data.items))
		})  
		<% }} %>
	},
	methods: {
		//验证规则检查
		check() {
			//验证规则
			let validRules = [
				<% for(let idx in  obj.required){
					var n = obj.required[idx] 
					var p=obj.properties[n] 
				%>
				    {name: '<%=n%>',title: '<%=p.title%>',required: true,/*minLength: 4*/ },
				<% } %>
			];
			return this.$validate.valid(this.postForm, validRules);
		},
		//保存公共方法
		_save(url){
			//提前检查是否登录
			if(!api.checkLogin()){
				return false;
			}
			//验证规则检查			
			var r = this.check();
			if (!r.isOk) { 
				this.$util.msg(r.msg);
				return; 
			} 
			var that = this;
			function save() {//保存方法
				api.submit(
					url,//提交的服务器api地址
					that.postForm,//提交的表单数据
					function(res) {
						//回调函数：保存成功跳转到列表页面
						that.$util.msg(res.msg)
						that.$util.goTo(that.$store.state.pages.{{{dir}}}.{{{name}}}.list.path);
					}
				);
			}
			if (this.imgList.length > 0) { //有图片则先上传图片
				api.upload({
					path: that.imgList[0],
					callback: function(res) {										
						res = JSON.parse(res.data);						
						if(!res.status){
							that.$util.msg(res.msg)
						}else{//再提交保存
						    that.postForm.pic=res.data.path;//将上传后的图片地址保赋值给要提交的表单数据
							save();
						}					
					}
				});
			} else {//否则直接保存
				save();
			}
		},
		submit(e) {//提交	
			//增加 删除id属性
			delete this.postForm.id
			this._save(this.$store.state.pages.{{{dir}}}.{{{name}}}.add.url)
		},
		getDetail(){//修改 获取详细信息	  
			http.get(this.$store.state.pages.{{{dir}}}.{{{name}}}.detail.url+"/"+this.postForm.id).then(res=>{      
				if(res.status){
					this.postForm=this.$util.formCopy(this.postForm, res.data)//将获取的数据复制到表单对象
				}
			}) 
		},
		update(){//修改 
		    this._save(this.$store.state.pages.{{{dir}}}.{{{name}}}.update.url)
		},
		chooseImage() {
			var that = this; 
			uni.chooseImage({
				count: that.uploadImgCount, 
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: res => {
					if (this.imgList.length != 0) {
						this.imgList = this.imgList.concat(res.tempFilePaths);
					} else {
						this.imgList = res.tempFilePaths;
					}
				}
			});
		},
		viewImage(e) {
			uni.previewImage({
				urls: this.imgList,
				current: e.currentTarget.dataset.url
			});
		},
		delImg(e) {
			var that = this;
			this.$refs.modal.open(function() {
				that.imgList.splice(e.currentTarget.dataset.index, 1);
			});
		},
		randomColor(idx) {
			if (idx >= this.colors.length) {
				idx = idx % this.colors.length;
			}
			return this.colors[idx];
		},
		
		<% for(let k in  obj.properties){
			var v = obj.properties[k] 
			if(v.type=="datetime"){									    
		%>
		{{{k}}}Change(e) {
			this.postForm.{{{k}}} = e.detail.value
		},
		
		<% }} %>
	},
	computed: {
		...mapState('base', ['tags', 'publish', 'colors']),
		title() { 
			return this.postForm.id?this.$store.state.pages.{{{dir}}}.{{{name}}}.update.text:this.$store.state.pages.{{{dir}}}.{{{name}}}.add.text
		}
	}
};
</script>

<style>
page {
	background: #ffffff;
}

.cu-form-group {
	/*border: none;*/
}
.cu-form-group.title {	
	/*border-bottom: 1px solid #eee;*/
}
.cu-form-group textarea{
	height: 200rpx;
}
.cu-form-group + .cu-form-group {
	/*border-top: 0;*/
}

.cu-form-group.tag-title {
	margin-top: 35rpx;
	border-top: 1px solid #eee;
}

.cu-form-group .title {
	min-width: calc(4em + 15px);	
}

.cu-bar .action.text-xs {
	font-size: 12px;
}

.img-list {
	padding-top: 14px;
}
/*数据列表*/
.picker /deep/ .input-value-border{
	border:none
}
</style>
